package com.zyz.forum_test.core;


import com.zyz.forum_test.exception.AppException;
import com.zyz.forum_test.util.ScreenshotUtil;
import com.zyz.forum_test.util.ScrollUtil;
import com.zyz.forum_test.util.WebDriverUtil;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;


/**
 * 帖子模块测试
 */
public class Invitation {

    private static final WebDriver driver = WebDriverUtil.getDriver();

    private static final WebDriverWait driverWait = new WebDriverWait(driver, Duration.ofSeconds(5));
    /**
     * 发布帖子
     */
    public void addInvitation(String username, String password ,String title, String content) throws InterruptedException {
        String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
        driver.get("http://127.0.0.1:1010/sign-in.html");
        // 检查logo显示状态
        By logoBy = By.cssSelector("body > div.page.page-center > div > div > div:nth-child(1) > div > div.text-center.mb-4 > img");
        driverWait.until(ExpectedConditions.presenceOfElementLocated(logoBy));

        // 检查背景图是否正常加载
        By image = By.cssSelector("body > div.page.page-center > div > div > div.col-lg.d-none.d-lg-block > img");
        driverWait.until(ExpectedConditions.presenceOfElementLocated(image));

        loginInput(driverWait, driver, methodName, username, password);

        // 判断是否正确跳转
        WebElement isAvatarExit = driverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#index_nav_avatar")));
        if (isAvatarExit != null) {
            System.out.println("登陆成功测试完毕");
        }
            // 点击发布帖子按钮
            driverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#bit-forum-content > " +
                    "div.page-header.d-print-none > div > div > div.col-auto.ms-auto.d-print-none > div > " +
                    "a.btn.btn-primary.d-none.d-sm-inline-block.article_post"))).click();
            // 查看跳转
            String publishTitle = driverWait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("#bit-forum-content > " +
                    "div.page-header.d-print-none > div > div > div > h2"))).getText();
            if (!"发新贴".equals(publishTitle)) throw new AppException("跳转帖子发布界面失败");
            driverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#bit-forum-content > div.page-body " +
                    "> div > div > div.card-body > div:nth-child(1) > select"))).click();
            // 选中下拉框中的面试宝典
            driverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#article_post_borad > option:nth-child(5)"))).click();
            // 选中标题输入框
            driverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#bit-forum-content > div.page-body > div " +
                    "> div > div.card-body > div:nth-child(2) > input"))).sendKeys(title);
            // 选中内容框 输入内容
            // CodeMirror 编辑器是一种特殊的富文本编辑器，直接向内部元素输入可能无效。需要通过 JavaScript 调用其 API：
            String script = "var editor = document.querySelector('.CodeMirror').CodeMirror;editor.setValue('"+ content +"');";
            ((JavascriptExecutor)driver).executeScript(script);
            // 点击发布按钮
            WebElement button = driverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#bit-forum-content > div.page-body " +
                    "> div > div > div.card-footer.bg-transparent.mt-auto > div >#article_post_submit")));
            ScrollUtil.scrollToElement(driver,button);
            Thread.sleep(500);
            button.click();
            // 跳转首页表示成功
            String mainTitle = driverWait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("#artical-items-body > div:nth-child(1) > div > div.col > div.text-truncate > a > strong"))).getText();
            if (!title.equals(mainTitle)) throw new AppException("帖子发布失败");

            System.out.println("发布帖子测试完毕");

    }

    /**
     * 点赞和评论回复
     * @param content
     */
    public void addLikeAndReply(String content) throws InterruptedException {
        String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();

            // 找到对应的标题帖子
            driverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#artical-items-body > div:nth-child(1) > div > div.col > div.text-truncate > a > strong"))).click();
            // 查看界面跳转情况
            driverWait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("#bit-forum-content > div.page-body " +
                    "> div > div > div:nth-child(1) > div.col-9.card.card-lg > div.card-body > #details_article_content_title")));
            // 定位点赞按钮
            driverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#bit-forum-content > div.page-body " +
                    "> div > div > div:nth-child(1) > div.col-9.card.card-lg > div.card-footer.bg-transparent.mt-auto.justify-content-end " +
                    "> div > div:nth-child(1) > div > #details_btn_like_count"))).click();
            // 是否点赞成功
            String likeSuccess = driverWait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("body > div.jq-toast-wrap.bottom-right > div > h2"))).getText();
            if (!"success".equals(likeSuccess)) throw new AppException("点赞异常");
            // 找到评论框输入内容
            String script = "var editor = document.querySelector('.CodeMirror').CodeMirror;editor.setValue('"+ content +"');";
            ((JavascriptExecutor)driver).executeScript(script);
            // 点击回复按钮
            WebElement buttonElem = driverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#details_btn_article_reply > span")));
            ScrollUtil.scrollToElement(driver,buttonElem);
            Thread.sleep(500);
            ((JavascriptExecutor)driver).executeScript("arguments[0].click()",buttonElem);
            // 查看是否回复成功
            Thread.sleep(500);
            String replay = driverWait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("#details_reply_area > div:nth-child(1) > div:nth-child(2) > div > div > p"))).getText();
            if (!content.equals(replay)) throw new AppException("回复失败");

            System.out.println("点赞评论测试完毕");

    }

    /**
     * 帖子编辑
     */
    public void editInvitation(String newTitle, String newContent) throws InterruptedException {
        String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
            Thread.sleep(500);
            // 点击进入帖子详情页
            driverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#artical-items-body > div:nth-child(1) > div > div.col > div.text-truncate > a > strong"))).click();
            // 滚动界面找到编辑按钮
            WebElement editButtonElem = driverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#bit-forum-content > div.page-body" +
                    " > div > div > div:nth-child(1) > div.col-9.card.card-lg > div.card-footer.bg-transparent.mt-auto.justify-content-end " +
                    "> div > div:nth-child(2) > div > #details_artile_edit")));
            ScrollUtil.scrollToElement(driver,editButtonElem);
            Thread.sleep(500);
            editButtonElem.click();
            // 检查是否跳转到编辑页面
            String editTitle = driverWait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("#bit-forum-content > div.page-header.d-print-none" +
                    " > div > div > div > h2"))).getText();
            if (!"编辑".equals(editTitle)) throw new AppException("跳转编辑页面失败");
            // 选中标题输入框
            WebElement titleInputElem = driverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#bit-forum-content > div.page-body > div > div > div > div " +
                    "> div.card-body > div:nth-child(3) > div.col-10>#edit_article_title")));
            titleInputElem.clear();
            titleInputElem.sendKeys(newTitle);
            // 选中内容框 输入内容
            // CodeMirror 编辑器是一种特殊的富文本编辑器，直接向内部元素输入可能无效。需要通过 JavaScript 调用其 API：
            String script = "var editor = document.querySelector('.CodeMirror').CodeMirror;editor.setValue('"+newContent+"');";
            ((JavascriptExecutor)driver).executeScript(script);
            // 向下滚动到提交按钮
            WebElement buttonElem = driverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#bit-forum-content > div.page-body >" +
                    " div > div > div > div > div.card-footer.bg-transparent.mt-auto > div > div > div>#edit_article_submit")));
            ScrollUtil.scrollToElement(driver,buttonElem);
            Thread.sleep(500);
            // 点击按钮
            buttonElem.click();
            // 如果跳转到首页表示成功
            String mainTitle = driverWait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("#bit-forum-content > div.page-header.d-print-none" +
                    " > div > div > div.col>#article_list_board_title"))).getText();
            if (!"首页".equals(mainTitle)) throw new AppException("编辑失败");

            System.out.println("编辑帖子测试完毕");
    }

    /**
     * 删除帖子
     */
    public void deleteInvitation() {
        String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();

            // 关闭站内信界面
            driverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#index_message_offcanvasEnd > " +
                    "div.offcanvas-header > button"))).click();
            // 点击进入帖子详情页
            driverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#artical-items-body > div:nth-child(1)" +
                    " > div > div.col > div.text-truncate > a > strong"))).click();
            // 查看跳转 定位删除按钮
            driverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#bit-forum-content > div.page-body " +
                    "> div > div > div:nth-child(1) > div.col-9.card.card-lg > div.card-footer.bg-transparent.mt-auto.justify-content-end " +
                    "> div > div:nth-child(3) > div > a"))).click();
            // 定位弹窗中的删除按钮
            driverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#details_delete_modal > div > " +
                    "div > div.modal-footer > div > div > div:nth-child(2)>#details_artile_delete"))).click();
            // 跳转到首页表示成功
            String mainTitle = driverWait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("#bit-forum-content > div.page-header.d-print-none" +
                    " > div > div > div.col>#article_list_board_title"))).getText();
            if (!"首页".equals(mainTitle)) throw new AppException("帖子删除失败");

            System.out.println("删除帖子测试完毕");
    }

    /**
     * 站内信发送和回复
     */
    public void siteMessage(String username1,String password1,String username2, String password2, String sendContent) {
        String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();

            // 点击退出切换账号发送站内信
            driverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("body > div.page > " +
                    "header.navbar.navbar-expand-md.navbar-light.d-print-none > div > div > div.nav-item.dropdown > a >#index_nav_avatar"))).click();
            driverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#index_user_logout > span"))).click();
            // 进行登录
            loginInput(driverWait,driver,methodName,username1,password1);
            // 点击进入帖子详情
            driverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#artical-items-body > div > div " +
                    "> div.col > div.text-truncate > a > strong"))).click();
            // 点击发私信按钮
            driverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#div_details_send_message>" +
                    "#btn_details_send_message"))).click();
            // 选中内容输入框
            driverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#index_message_modal > div > " +
                    "div > div.modal-body > div > div > div>#index_message_receive_content"))).sendKeys(sendContent);
            // 点击发送按钮
            driverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#index_message_modal > div > " +
                    "div > div.modal-footer>#btn_index_send_message"))).click();
            // 如果右下角出现了弹窗表示成功
            String successStr = driverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("body > div.jq-toast-wrap.bottom-right > div > h2"))).getText();
            if (!"success".equals(successStr)) throw new AppException("站内信发送失败");
            // 发送成功后退出登录  使用username2进行查看
            driverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("body > div.page > " +
                    "header.navbar.navbar-expand-md.navbar-light.d-print-none > div > div > div.nav-item.dropdown > a >#index_nav_avatar"))).click();
            // 点击退出
            driverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#index_user_logout > span"))).click();
            // 进行登录
            loginInput(driverWait,driver,methodName,username2,password2);
            // 点击右上角小铃铛
            driverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("body > div.page >" +
                    " header.navbar.navbar-expand-md.navbar-light.d-print-none > div > div > div:nth-child(2) > div > a > svg"))).click();
            // 如果有消息表示成功
            driverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#index_div_message_list > div:nth-child(1) > " +
                    "div > div.col.text-truncate > a")));

            System.out.println("站内信测试完毕");
    }

    private static void loginInput(WebDriverWait driverWait, WebDriver driver, String functionName, String userName, String password) {
        // 检查输入
        By userInputBy = By.cssSelector("#username");
        By passwordBy = By.cssSelector("#password");
        WebElement userInputElem = driverWait.until(ExpectedConditions.presenceOfElementLocated(userInputBy));
        if (userInputElem == null) {
            ScreenshotUtil.screenshot(driver, functionName);
            throw new AppException("用户名输入框加载异常");
        }
        WebElement passwordElem = driverWait.until(ExpectedConditions.presenceOfElementLocated(passwordBy));
        if (passwordElem == null) {
            ScreenshotUtil.screenshot(driver, functionName);
            throw new AppException("密码输入框加载异常");
        }
        // 检查按钮
        By submitBy = By.cssSelector("#submit");
        WebElement submitElem = driverWait.until(ExpectedConditions.presenceOfElementLocated(submitBy));
        if (submitElem == null) {
            ScreenshotUtil.screenshot(driver, functionName);
            throw new AppException("登陆按钮加载异常");
        }
        userInputElem.sendKeys(userName);
        passwordElem.sendKeys(password);
        submitElem.click();


    }





}
